﻿using System.ComponentModel.Composition;
using Polenter.Mcm;

namespace McmWinFormsApplication1.Components
{
    [Export(typeof (McmComponent))]
    public class ReverseTextComponent : McmComponent
    {
        /// <summary>
        ///     CommandExecutor executes a command in ThreadPool.
        ///     Additionaly it reports when the command is finished.
        /// </summary>
        private readonly CommandAsyncExecutor<ReverseTextCommand> _ReverseTextCommandExecutor;

        public ReverseTextComponent()
        {
            _ReverseTextCommandExecutor = new CommandAsyncExecutor<ReverseTextCommand>();
            _ReverseTextCommandExecutor.ExecuteCompleted += on_ReverseTextCommandExecutor_ExecuteCompleted;
        }

        private void on_ReverseTextCommandExecutor_ExecuteCompleted(object sender,
                                                                    CommandEventArgs<ReverseTextCommand> e)
        {
            // create the response message telling about the last error
            ReverseTextResponseMessage m = new ReverseTextResponseMessage(e.Command.Error);
            if (!m.HasError)
            {
                // no error occured, 
                // set message properties from the command result
                m.OutputText = e.Command.Result.OutputText;
            }

            // Broadcast the message
            Components.Messages.Post(m);
        }

        [MessageSubscriber(McmComponentContainer.MessagesChannelName)]
        private void handleReverseTextRequestMessage(ReverseTextRequestMessage m)
        {
            // create command argument
            ReverseTextCommandArgument arg = new ReverseTextCommandArgument();

            arg.InputText = m.InputText;

            // create the command using the argument above
            ReverseTextCommand c = new ReverseTextCommand(arg);

            // execute the command
            _ReverseTextCommandExecutor.ExecuteAsync(c);
        }
    }
}